import webpack from "webpack";
import symbol from 'log-symbols';
import chalk from 'chalk';
import ora from "ora";
const config = require('./webpack.build.js');
const exec = require("child_process").exec;
const tool = require('./tool.js');
const merge = require('webpack-merge');
const util = require('./util.js');
const path = require('path');

let build = async () => {
    const siteName = await util.getRunPath();

    const baseConfig = merge(config(siteName), tool.getUserConfig());
    console.log( symbol.success , chalk.green('开始打包'));
    webpack(baseConfig, async (error) => {
        if(error !== null){
            console.log(symbol.error, chalk.greenBright(error));
        }else{
            setTimeout(() => {
                loadCmd(`rm main.js`, '删除main.js', './dist/js')
            });
            console.log(symbol.success, chalk.green('打包完成'));
        }
        // process.exit(1);
    });
}


let loadCmd = async (cmd, text, cd) => {
    let loading = ora();
    loading.start(`${text}: 命令执行中...`);
    if (cd){
        await exec(cmd, {cwd: path.resolve(process.cwd(), cd), detached: true, shell: true});
    } else {
        await exec(cmd);
    }
    loading.succeed(`${text}: 命令执行完成`);
}

module.exports = build;

